//
//  ZCenterPersonalInfoViewController.m
//  shopSN
//
//  Created by chang on 16/7/17.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZCenterPersonalInfoViewController.h"
#import "ZYSLoginViewController.h"//亿速登录

#import "ZChangeNameViewController.h"    //修改姓名
#import "ZChangePersonIDViewController.h"//修改身份证号
#import "ZChangeGenderViewController.h"  //修改性别
#import "ZChangePhoneViewController.h"   //修改手机号
#import "ZChangePasswordViewController.h"//修改密码
#import "ZReceiveAddressViewController.h"//收货地址

#import "ZPersonInfoModel.h" //信息model

@interface ZCenterPersonalInfoViewController ()<UITableViewDataSource, UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UITableView *_tableView;
    UIImageView *_headIV;  //头像
}

/**更换头像 选择按钮标题数组 */
@property (strong,nonatomic) NSArray *titleArr;
/**右侧数据*/
@property (nonatomic,strong) NSArray *rightInfoArr;


/** 更换头像 弹出框 */
@property (strong,nonatomic) UIView *iconImageView;

/** 修改生日日期 弹出框 */
@property (strong,nonatomic) UIView *chooseDateView;

@property (strong,nonatomic) NSString *birthDayStr;

//日期选择部分
/**
 *  日期选择视图
 */
@property (strong,nonatomic) UIView *ourDatPicker;
@property (strong,nonatomic) UIButton *datecancelBtn;
@property (strong,nonatomic) UIButton *datesureBtn;
@property (strong,nonatomic) UIDatePicker *datePicker;



@end

@implementation ZCenterPersonalInfoViewController
#pragma mark - ==== 页面设置 =====
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLb.text = @"个人信息";
    //初始化 中间视图 相关子视图
    self.mainMiddleView.backgroundColor = __AccountBGColor;
    [self initSubViews:self.mainMiddleView];
//    [self getIntetfacePersonInfo];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getIntetfacePersonInfo];
}
#pragma mark - 中间视图部分 相关子视图
//初始化相关子视图
- (void)initSubViews:(UIView *)view {
    
    //标题数组
    _titleArr = [NSArray array];
    _titleArr = @[@"头像",@"姓名",@"身份证号",@"性别",@"生日",@"手机号",@"登录密码",@"我的收货地址"];
    _rightInfoArr = @[];
    
    //个人信息表
//    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, __kWidth, __kHeight-140)];
//  _tableView.backgroundColor = LH_RGBCOLOR(230, 230, 230);
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectW(view), CGRectH(view)-115)];
    [view addSubview:_tableView];
    _tableView.backgroundColor = __AccountBGColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.contentSize = CGSizeMake(__kWidth, 388);
    
    //退出登录 按钮
    UIButton *exitBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, CGRectYH(_tableView)+25, CGRectW(view)-30, 30)];
    [view addSubview:exitBtn];
    exitBtn.backgroundColor = __DefaultColor;
    exitBtn.layer.cornerRadius = 3.0f;
    exitBtn.titleLabel.font = MFont(15);
    [exitBtn setTitle:@"退出登录" forState:BtnNormal];
    [exitBtn setTitleColor:[UIColor whiteColor] forState:BtnNormal];
    [exitBtn addTarget:self action:@selector(exitAction) forControlEvents:BtnTouchUpInside];
    
    
}


#pragma mark *** 获取网络个人信息 ***
-(void)getIntetfacePersonInfo{
    
    NSDictionary *params =@{@"token":[UdStorage getObjectforKey:Userid]};

    [ZHttpRequestService POST:@"User/userInfo" withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            
            NSLog(@"jsondic---%@",jsonDic[@"data"]);
            NSDictionary *data = jsonDic[@"data"];
            NSArray *list = data[@"user"];
            NSDictionary *dic = list[0];
            NSMutableArray *arr1 = [@[] mutableCopy];
            if (IsNull(dic[@"realname"])) {
               [arr1 addObject:@""];
            }else{
               [arr1 addObject:dic[@"realname"]];
            }

            [arr1 addObject:dic[@"idcard"]];
            [arr1 addObject:dic[@"sex"]];
            [arr1 addObject:dic[@"birthday"]];
            [arr1 addObject:dic[@"user_header"]];
            NSMutableArray *arr2 = [@[] mutableCopy];
            [arr2 addObject:dic[@"mobile"]];
            [arr2 addObject:@"修改密码"];
            [arr2 addObject:@"查看地址"];
            _rightInfoArr = @[arr1,arr2];
            [_tableView reloadData];
        //存入单例
            [ZPersonInfoModel shareInfoModel].infoArr = jsonDic[@"data"][@"address"];
            
        }else{
            NSString *message = jsonDic[@"message"];
            
            [SXLoadingView showAlertHUD:message duration:2];
        }
    } failure:^(NSError *error) {
        
        [SXLoadingView showAlertHUD:@"失败" duration:SXLoadingTime];
        
    } animated:true withView:nil];
}

#pragma mark- ===== tableView DataSource and Delegate =====
//section
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

//row
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 5;
    }else{
        return 3;
    }
}

//cell
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.accessoryType= UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = MFont(13);
    cell.textLabel.textColor = HEXCOLOR(0x565656);
    cell.detailTextLabel.font = MFont(13);
    cell.detailTextLabel.textColor = HEXCOLOR(0x565656);
    cell.textLabel.text = _titleArr[indexPath.section*5+indexPath.row];
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            _headIV = [[UIImageView alloc]initWithFrame:CGRectMake(__kWidth-95, 5, 60, 60)];
            [cell.contentView addSubview:_headIV];
            if (_rightInfoArr.count!=0){
            [_headIV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HomeADUrl,_rightInfoArr[0][4]]] placeholderImage:MImage(@"touxiang")];
            }
            //*添加边线 更换相册图片效果不好
            _headIV.layer.cornerRadius=30;
            _headIV.layer.masksToBounds = YES;
        }else{
            if (_rightInfoArr.count!=0) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",_rightInfoArr[0][indexPath.row-1]];;
            }
        }
    }else{
        if (_rightInfoArr.count!=0) {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",_rightInfoArr[1][indexPath.row]];;
        }

        
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0) {
        switch (indexPath.row) {
            case 0:
            {
                [self changeImage];
            }
                break;
            case 1:
            {
                ZChangeNameViewController *vc = [[ZChangeNameViewController alloc]init];
                vc.realName=_rightInfoArr[0][0];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 2:
            {
                ZChangePersonIDViewController *vc=[[ZChangePersonIDViewController alloc]init];
                vc.personID = _rightInfoArr[0][1];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 3:
            {
                ZChangeGenderViewController *vc = [[ZChangeGenderViewController alloc]init];
                vc.genderStr = _rightInfoArr[0][2];

                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            default:{
                [self chooseData];
            }
                break;
        }
    }else{
        switch (indexPath.row) {
            case 0:
            {
                ZChangePhoneViewController *vc = [[ZChangePhoneViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 1:
            {
                ZChangePasswordViewController *vc = [[ZChangePasswordViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            default:{
                ZReceiveAddressViewController *vc = [[ZReceiveAddressViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0 &&indexPath.row==0) {
        return 70;
    }else{
        return 44;
    }
}



-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section) {
        UIView *sectionV=[[UIView alloc]initWithFrame:CGRectMake(0, 0, __kWidth, 10)];
        sectionV.backgroundColor = [UIColor clearColor];
        return sectionV;
    }else{
        return nil;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section) {
        return 10;
    }else{
        return 0;
    }
}

#pragma mark - ==== 退出登录 =====
//退出登录
-(void)exitAction{
    NSLog(@"退出登录");
    
    //清除记录
    NSString *nilStr = nil;
    [UdStorage storageObject:nilStr forKey:Userid];
    [UdStorage storageObject:nilStr forKey:UserType];
    [UdStorage storageObject:nilStr forKey:UserPhone];

    [ZHttpRequestService POST:@"Login/logOut" withParameters:nil success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {

        }
    } failure:^(NSError *error) {

    } animated:YES withView:nil];
    
    
    //重新登录
//    ZLoginViewController *vc = [[ZLoginViewController alloc] init];
    ZYSLoginViewController *vc = [[ZYSLoginViewController alloc]init];
    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark ===== 更换头像 =====

-(void)changeImage{
    //弹出框
    _iconImageView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)];
    _iconImageView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.5f];
    [self.view addSubview:_iconImageView];
    
    //选择菜单视图
    //***原发文件内容
//    UIView *menuView = [[UIView alloc] initWithFrame:CGRectMake(0, __kHeight-140, __kWidth, 140)];
//    menuView.backgroundColor = HEXCOLOR(0xe9e9ee);
//    [_iconImageView addSubview:menuView];
//    
//    NSArray *array = @[@"拍照", @"从手机相册选择", @"取消"];
//    for (NSInteger i=0; i<array.count; i++) {
//        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 1+i*42+(i==2?10:0), __kWidth-20, 40)];
//        btn.backgroundColor = HEXCOLOR(0xf1f1f1);
//        [btn setTitleColor:HEXCOLOR(0x333333) forState:UIControlStateNormal];
//        if (i==2) {
//            btn.backgroundColor = [UIColor whiteColor];
//            [btn setTitleColor:HEXCOLOR(0x333333) forState:UIControlStateNormal];
//        }
//        btn.titleLabel.font = MFont(12);
//        [btn setTitle:array[i] forState:UIControlStateNormal];
//        [btn addTarget:self action:@selector(iconBtnAction:) forControlEvents:BtnTouchUpInside];
//        btn.tag = 11+i;
//        [menuView addSubview:btn];
//    }
    
    //*** 按设计修改后内容
    NSArray *array = @[@"拍照", @"我的相册", @"取消"];
    //1 菜单视图 选择拍照或相册
    UIView *chooseView = [[UIView alloc] initWithFrame:CGRectMake(10, __kHeight-172, __kWidth-20, 102)];
    chooseView.backgroundColor = HEXCOLOR(0xffffff);
    [_iconImageView addSubview:chooseView];
    chooseView.layer.cornerRadius = 10.0f;
    
    //1.1 中间分隔线
    UIImageView *lineIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 51, CGRectW(chooseView), 1)];
    [chooseView addSubview:lineIV];
    lineIV.backgroundColor = HEXCOLOR(0xdedede);
    
    //1.2 选择拍照或相册 按钮
    //    按钮颜色 color(0 84 255)  (0x0051ff)
    for (NSInteger i=0; i<array.count-1; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, i*52, CGRectW(chooseView), 50)];
//        btn.backgroundColor = HEXCOLOR(0xf1f1f1);
        [btn setTitleColor:HEXCOLOR(0x0051ff) forState:BtnNormal];
//        btn.titleLabel.font = MFont(15);
        [btn setTitle:array[i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(iconBtnAction:) forControlEvents:BtnTouchUpInside];
        btn.tag = 160+i;
        [chooseView addSubview:btn];
    }
    
    
    //2 菜单视图 选择 取消
    UIView *cancelView = [[UIView alloc] initWithFrame:CGRectMake(10, CGRectYH(chooseView)+10, __kWidth-20, 50)];
    cancelView.backgroundColor = HEXCOLOR(0xffffff);
    [_iconImageView addSubview:cancelView];
    cancelView.layer.cornerRadius = 10.0f;
    
    //2.1 按钮
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, CGRectW(cancelView), 50)];
    [cancelView addSubview:cancelBtn];
    [cancelBtn setTitleColor:HEXCOLOR(0x0051ff) forState:BtnNormal];
//  cancelBtn.titleLabel.font = MFont(15);
    [cancelBtn setTitle:array[2] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(iconBtnAction:) forControlEvents:BtnTouchUpInside];
    cancelBtn.tag = 162;

    
    
}

- (void)iconBtnAction:(UIButton *)btn {
    switch (btn.tag - 160) {
        case 0: {
            NSLog(@"拍照");
            UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
            pickerVC.delegate = self;
            //选择照片数据源 ---默认是相册
            pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickerVC animated:YES completion:nil];
        }
            
            
            break;
        case 1: {
            NSLog(@"从相册获取");
            UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
            //想要知道选择的图片
            pickerVC.delegate = self;
            //开启编辑状态
            pickerVC.allowsEditing = YES;
            [self presentViewController:pickerVC animated:YES completion:nil];
            [_iconImageView removeFromSuperview];
        }
            
            break;
        default:
            NSLog(@"取消");
            [_iconImageView removeFromSuperview];
            break;
    }
}

#pragma mark - 更换头像Delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    _headIV.image = info[UIImagePickerControllerOriginalImage];
    if (picker.allowsEditing) {
        _headIV.image = info[UIImagePickerControllerEditedImage];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    //保存图片进入沙盒中
    [self saveImage:_headIV.image withName:@"headImage"];
}

#pragma mark - 上传头像
-(void)saveImage:(UIImage*)headImage withName:(NSString*)imageName{
    NSData *imageData = UIImageJPEGRepresentation(headImage, 0.5);

    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];

    // 将图片保存到 document
    [imageData writeToFile:fullPath atomically:NO];
    [UdStorage storageObject:fullPath forKey:UserHead];

    [ZHttpRequestService POST:@"User/uploadFileToServer" Params:@{@"token":[UdStorage getObjectforKey:Userid]} NSData:imageData key:@"header" success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
         if (succe) {
              [SXLoadingView showAlertHUD:@"修改头像成功" duration:SXLoadingTime];
         }
     } failure:^(NSError *error) {
         [SXLoadingView showAlertHUD:@"修改头像失败" duration:SXLoadingTime];
     } animated:YES];

}




#pragma mark - 选择生日日期
-(void)chooseData{
    //日期选择 弹出框
    _chooseDateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)];
    [self.view addSubview:_chooseDateView];
    _chooseDateView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.5f];
    
    // 日期视图
    UIView *dateView = [[UIView alloc]initWithFrame:CGRectMake(0, __kHeight-200, __kWidth, 200)];
    [_chooseDateView addSubview:dateView];
    dateView.backgroundColor = HEXCOLOR(0xffffff);
    
    //1 按钮视图
    UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectW(dateView), 40)];
    [dateView addSubview:btnView];
    btnView.backgroundColor = __AccountBGColor;
    
    // 按钮字体颜色  color(0 84 255)  (0x0051ff)
    //2 确定按钮
    _datesureBtn = [[UIButton alloc]initWithFrame:CGRectMake(__kWidth-55, 10, 40, 20)];
    [btnView addSubview:_datesureBtn];
    _datesureBtn.titleLabel.font = MFont(15);
    [_datesureBtn setTitle:@"确定" forState:BtnNormal];
    [_datesureBtn setTitleColor:HEXCOLOR(0x0051ff) forState:BtnNormal];
    [_datesureBtn addTarget:self action:@selector(dateSureBtnAction) forControlEvents:BtnTouchUpInside];
    
    //3 取消按钮
    _datecancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 10, 40, 20)];
    [btnView addSubview:_datecancelBtn];
    _datecancelBtn.titleLabel.font = MFont(15);
    [_datecancelBtn setTitle:@"取消" forState:BtnNormal];
    [_datecancelBtn setTitleColor:HEXCOLOR(0x0051ff) forState:BtnNormal];
    [_datecancelBtn addTarget:self action:@selector(dateCancelBtnAction) forControlEvents:BtnTouchUpInside];
    
    //日期选择 datePicker
    _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, __kWidth, 160)];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    [dateView addSubview:_datePicker];
    
}

#pragma mark - dateSure and dateCancel
-(void)dateSureBtnAction{
    NSLog(@"%@", NSStringFromSelector(_cmd));

    NSDateFormatter *formatter =[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    _birthDayStr = [NSString stringWithFormat:@"%@",[formatter stringFromDate:self.datePicker.date]];
    [_tableView reloadData];
    [_chooseDateView removeFromSuperview];
    
    
    NSDictionary *params =@{@"birthday":_birthDayStr,@"token":[UdStorage getObjectforKey:Userid]};
    
    [ZHttpRequestService POST:@"User/changeBirthday" withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            
            NSLog(@"xiugai--%@",jsonDic);
//            NSString *message = jsonDic[@"message"];
//            [SXLoadingView showAlertHUD:message duration:1.5];

        }else{
            NSString *message = jsonDic[@"message"];
            
            [SXLoadingView showAlertHUD:message duration:2];
        }
    } failure:^(NSError *error) {
        
        [SXLoadingView showAlertHUD:@"失败" duration:SXLoadingTime];
        
    } animated:true withView:nil];
    
    
}
-(void)dateCancelBtnAction{
    _birthDayStr = nil;
    [_tableView reloadData];
    [_chooseDateView removeFromSuperview];
}
- (void)dateChanged:(id)sender
{
    
    NSLog(@"%@", NSStringFromSelector(_cmd));
    _datePicker = (UIDatePicker *)sender;
    NSDateFormatter *formatter =[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    _birthDayStr = [NSString stringWithFormat:@"%@",[formatter stringFromDate:_datePicker.date]];
    _rightInfoArr[0][3] = _birthDayStr;
    
    NSLog(@"%@",_birthDayStr);
    [_tableView reloadData];
    
}





#pragma mark - ==== others =====
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
